<?php

namespace app\index\controller;

use addons\wechat\model\WechatCaptcha;
use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Attachment;
use think\Config;
use think\Cookie;
use think\Hook;
use think\Request;
use think\Session;
use think\Validate;

use fast\Random;
use PDO;
use think\Response;
use think\cache\driver\Redis;
use think\Db;

/**
 * 团队
 */
class Team extends Frontend
{
    protected $layout = '';
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 首页
     */
    public function index()
    {
        $this->assign("title", "我的团队");

        $this->assign("foot_nav_index", "4");

        return $this->view->fetch();
    }

    /**
     * 达人任务-任务列表
     */
    public function darenteamleventask()
    {
        $this->assign("title", "任务列表");

        $this->assign("foot_nav_index", "4");

        return $this->view->fetch();
    }


    /**
     * 达人任务-补单
     */
    public function darentotask()
    {

        $this->assign("title", "补单");

        $this->assign("foot_nav_index", "5");

        $pid = input("pid");
        $ceng = input("ceng");

        $this->assign("pid", $pid);
        $this->assign("ceng", $ceng);
        return $this->view->fetch();
    }


    /**
     * 我的推荐
     */
    public function nteams()
    {
        $this->assign("user_id", $this->auth->id);
        $this->assign("title", "我的推荐");
        $this->assign("foot_nav_index", "5");
        return $this->view->fetch();
    }

    /**
     * 我的推荐列表
     * */
    public function sonList()
    {
        $input = $this->request->param();

        $user_id = $this->auth->id;

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $mobile = isset($input['mobile']) ? $input['mobile'] : '';
        $page = isset($input['page']) ? $input['page'] : 1;
        $pagesize = isset($input['pagesize']) ? $input['pagesize'] : 10;

        $where['parent_ids'] = ['like', "%{$user_id}%"];
        if ($mobile) $where['mobile'] = ['like', "%{$mobile}%"];

        $list = Db::name('user')->field('id,avatar,nickname,mobile,jointime,parent_user_id')->where($where)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['mobile'] = hidtelphone($v['mobile']);
                $v['jointime'] = date('Y/m/d H:i', $v['jointime']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无数据');
        }

    }

    /**
     * 我的推荐团队
     */
    public function nteam_fetch()
    {
        $user = $this->auth->getUser();
        $page = input("page", 1);
        $keyword = $this->request->param('keyword', '');
        $listRows = 10;
        $where = [];
        if ($keyword != '') {
            $where = ['mobile' => ['like', "%{$keyword}%"]];
        }
        $list_info = db("user")->where("parent_user_id", $this->auth->id)->where($where)->order("id desc")->paginate($listRows, true, ["page" => $page]);

        $list = $list_info->items();
        foreach ($list as $key => $val) {
            $list[$key]["avatar"] = $val["avatar"] ? $val["avatar"] : "/assets/img/avatar.png";
            $list[$key]["username"] = $val["username"] ? $val["username"] : $val["mobile"];
            $list[$key]["nickname"] = $val["nickname"] ? $val["nickname"] : $val["mobile"];
            $list[$key]["mobile"] = hidtelphone($val["mobile"]);
            $list[$key]["createtime"] = date("Y/m/d H:i", $val["createtime"]);
            unset($list[$key]["password"]);
            unset($list[$key]["salt"]);
        }
        return json($list);
    }

    /*
     * 
     * 审核
     */
    public function auditUser()
    {
        $userId = $this->auth->id;
        $total = Db::name('expert_upgrade_order')->where(['up_user_id' => $userId, 'status' => ['>', 0]])->count();
        $this->assign('total', $total);
        $totalMoney = Db::name('expert_upgrade_order')->where(['up_user_id' => $userId, 'status' => ['>', 0]])->sum('order_amount');
        $this->assign('totalMoney', $totalMoney);


        return $this->view->fetch('audituser');
    }

    /*
     * 审核用户列表
     */

    public function auditUserList()
    {
        $status = $this->request->param('status', 0);
        $page = $this->request->param('page', 1);
        $where = [];
        if ($status == 1) {
            $where['o.status'] = ['in', [2, -2]];
        } else {
            $where['o.status'] = ['in', [1, -1]];
        }
        $list = Db::name("expert_upgrade_order")
            ->field("o.id,u.nickname,u.avatar,u.mobile,o.status,o.order_type,o.upgrade_type,o.expiretime,o.expiretime,o.is_expire_time")
            ->alias('o')
            ->join('user u', 'u.id=o.up_user_id')
            ->where(["o.up_user_id" => $this->auth->id])
            ->where($where)
            ->order("order_type ASC,o.id ASC")
            ->page($page, 10)->select();
        foreach ($list as $key => &$value) {
            $value['key'] = str_pad($key + 1 + (($page - 1) * 10), 2, "0", STR_PAD_LEFT);
            $value['avatar'] = ($value['avatar'] == '' ? '' : cdnurl($value['avatar'], true));
            $value['expiretime'] = $value['expiretime'] - time();
            $value['expiretime'] = ($value['expiretime'] > 0 ? $value['expiretime'] : 0);
            $value['mobile'] = hidtelphone($value['mobile']);
            $value['url'] = url('index/Team/auditInfo', ['id' => $value['id']]);

        }
        $this->success('', '', $list);

    }

    /*
     * 审核详细
     */

    public function auditInfo()
    {
        $id = $this->request->param('id');
        $value = Db::name("expert_upgrade_order")
            ->field("o.id,u.nickname,u.avatar,u.mobile,u.unique_id,o.status,o.order_type,o.upgrade_type,o.expiretime,o.order_sn,o.order_amount")
            ->alias('o')
            ->join('user u', 'u.id=o.up_user_id')
            ->where(["o.up_user_id" => $this->auth->id, 'o.id' => $id])
            ->find();
        $value['avatar'] = ($value['avatar'] == '' ? '' : cdnurl($value['avatar'], true));
        $value['expiretime'] = $value['expiretime'] - time();
        $value['expiretime'] = ($value['expiretime'] > 0 ? $value['expiretime'] : 0);
        $value['mobile'] = hidtelphone($value['mobile']);
        $value['order_sn'] = explode(',', $value['order_sn']);
        $this->assign('info', $value);
        return $this->view->fetch('audit_info');
    }

    /*
     * 设置超时时间
     */
    public function setOrderTime()
    {
        $id = $this->request->param('id');
        $order = Db::name("expert_upgrade_order")
            ->field("o.id,u.nickname,u.avatar,u.mobile,u.unique_id,o.status,o.up_user_id,o.order_type,o.upgrade_type,o.expiretime,o.order_sn,o.order_amount,o.user_id")
            ->alias('o')
            ->join('user u', 'u.id=o.up_user_id')
            ->where(["o.up_user_id" => $this->auth->id, 'o.id' => $id])
            ->find();
        if (!empty($order)) {
            if ($order['status'] == 1) {
                Db::transaction(function () use ($order) {
                    Db::name('user')->where(['id' => $this->auth->id])->setInc('expire_times');
                    Db::name("expert_upgrade_order")->data(['status' => 2, 'is_expire_time' => 1, 'checkedtime' => time()])->where(['id' => $order['id']])->update();
                    \app\admin\model\ExpertUpgradeOrder::hideUser($order['up_user_id']);
                });
                //查询是否完成全部任务,完成给他升级
                $ExpertUpgradeOrder = new \app\admin\model\ExpertUpgradeOrder();
                $ret = $ExpertUpgradeOrder->upLevel($order['user_id']);
                if (!$ret) {
                    \think\Log::write("审核升级失败！");
                }
                $this->success('ok');
            }
        }
        $this->error('on ok');
    }

    /*
     * 设置超时时间
     */
    public function clientOrderTimeOut()
    {
        $id = $this->request->param('id');
        $order = Db::name("expert_upgrade_order")
            ->field("o.id,u.nickname,u.avatar,u.mobile,u.unique_id,o.status,o.up_user_id,o.order_type,o.upgrade_type,o.expiretime,o.order_sn,o.order_amount,o.user_id")
            ->alias('o')
            ->join('user u', 'u.id=o.up_user_id')
            ->where(['o.id' => $id])
            ->find();
        if (!empty($order)) {
            if ($order['status'] == 1) {
                if (($order['expiretime'] - time()) <= 0) {
                    Db::transaction(function () use ($order) {
                        Db::name('user')->where(['id' => $order['up_user_id']])->setInc('expire_times');
                        Db::name("expert_upgrade_order")->data(['status' => 2, 'is_expire_time' => 1, 'checkedtime' => time()])->where(['id' => $order['id']])->update();
                        \app\admin\model\ExpertUpgradeOrder::hideUser($order['up_user_id']);
                    });
                    //查询是否完成全部任务,完成给他升级
                    $ExpertUpgradeOrder = new \app\admin\model\ExpertUpgradeOrder();
                    $ret = $ExpertUpgradeOrder->upLevel($order['user_id']);
                    if (!$ret) {
                        \think\Log::write("审核升级失败！");
                    }
                    $this->success('ok');
                }
            }
        }
        $this->error('on ok');
    }

    /*
     * 审核状态
     */

    public function setOrderStatus()
    {
        $id = $this->request->param('id');
        $status = $this->request->param('status');
        $note = $this->request->param('note');//驳回理由
        $data = [];
        switch ($status) {
            case -2:
                //                驳回
                if ($note == '') {
                    $this->error('请输入驳回理由！');
                }
                $data['note'] = $note;
                $data['status'] = -2;
                break;
            case 2:
                //                通过
                $data['status'] = 2;
                break;

            default:
                $this->error('非法操作！');
                break;
        }
        $data['checkedtime'] = time();
        $order = Db::name('expert_upgrade_order')->where(['id' => $id, "up_user_id" => $this->auth->id])->find();
        if (empty($order)) {
            $this->error('非法参数！');
        }
        if ($order['status'] != 1) {
            $this->success('已经处理！', url('index/Team/auditUser', '', false, true));
        }
        // 启动事务
        Db::startTrans();
        try {
            if ($order['upgrade_type'] == 4) {
                //加权分红
                $weightingTask = Db::name('user_weighting_task')->where(['user_id' => $order['user_id'], 'month' => date('Ym')])->find();
                $orderUserInfo = Db::name('user')->where(['id' => $order['user_id']])->find();
                if (empty($orderUserInfo)) {
                    throw new \Exception("异常订单，不存在的用户！");
                }
                if (empty($weightingTask)) {
                    $insetData = [];
                    $insetData['user_id'] = $order['user_id'];
                    $insetData['level'] = $order['level'];
                    $insetData['month'] = date('Ym');
                    $insetData['month_buy'] = 0;
                    $insetData['status'] = 0;
                    $insetData['add_time'] = time();
                    $weightingTaskId = Db::name('user_weighting_task')->insertGetId($insetData);
                } else {
                    $weightingTaskId = $weightingTask['id'];
                }
                $uprow = Db::name('user_weighting_task')->where(['id' => $weightingTaskId])->setInc('month_buy', 1);
                if (empty($uprow)) {
                    throw new \Exception("累加分红失败！");
                }
            }
            $row = Db::name('expert_upgrade_order')->where(['id' => $id])->data($data)->update();
            // 提交事务
            Db::commit();
            if ($data['status'] == 2 && $row > 0) {
                //查询是否完成全部任务,完成给他升级
                $ExpertUpgradeOrder = new \app\admin\model\ExpertUpgradeOrder();
                $ret = $ExpertUpgradeOrder->upLevel($order['user_id']);
            }

        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($row) {
            $this->success('操作成功！', url('index/Team/auditUser', '', false, true));
        }
        $this->error('异常操作！');
    }
}
